<script setup lang="ts">
import { onMounted } from 'vue';
import * as echarts from '/@/components/ec-canvas/echarts';
import { state } from './state';
import { navigateTo, getCurrentInstance } from '@tarojs/taro';
import {
  QUERY_ASSET_CHANGE_APPROVAL,
  QUERY_APPROVAL_PIE,
  QUERY_APPROVAL_CHART_BY_TIME,
  QUERY_APPROVAL_CHART_BY_STATUS,
} from '/@/api/modules/equipment/asset-change';
import { Search2 as AppNutIconSearch2 } from '@nutui/icons-vue-taro';
import dayjs from 'dayjs';
import {
  ASSET_CHANGE_ALTER_STATUS,
  ASSET_CHANGE_ALTER_STATUS_COLOR,
  ASSET_CHANGE_ALTER_STATUS_BG_COLOR,
} from '/@/common/constant';

/**
 * @description 列表查询
 * @param {Number} page -当前页
 * @param {Number} pageSize -每页条数
 */
function queryList(page: number = 1, pageSize: number = 15) {
  if (!page && state.finished) return;
  state.loading = true;

  QUERY_ASSET_CHANGE_APPROVAL({
    comQuery: { page, pageSize },
    code: state.keyword,
  })
    .then((res) => {
      state.loading = false;

      if (
        state.activePage >=
        (res.comQuery.pageCount ||
          (res.comQuery.totalCount as number) / (res.comQuery.pageSize as number) ||
          1)
      )
        state.finished = true;
      if (!res.changeDtoList || !res.changeDtoList.length) return;

      res.changeDtoList.forEach((item) => state.list.push(item));

      state.activePage += 1;
    })
    .catch(() => {
      state.loading = false;
    });
}

/**
 * @function 加载
 */
function onLoading() {
  if (state.finished) return;

  queryList(state.activePage);
}

function approveList() {
  state.activePage = 1;
  state.loading = true;
  state.finished = false;
  state.list = [];
  onLoading();
}

onMounted(() => {
  approveList();
  approveStatistics();
});

/**
 * 今日审批
 */
function todayApproveStatistics(startTime: number, endTime: number) {
  QUERY_APPROVAL_PIE({ startTime, endTime }).then((res) => {
    state.todayApprove = res.content?.value;
  });
}

/**
 * 本月审批
 */
function currentMonthApproveStatistics() {
  const startTime = dayjs().startOf('month').valueOf();
  const endTime = dayjs().endOf('month').valueOf();
  QUERY_APPROVAL_PIE({ startTime, endTime }).then((res) => {
    state.currentMonthApprove = res.content?.value;
  });
}

/**
 * 审批统计
 */
function approveStatistics() {
  const startTime = dayjs().hour(0).minute(0).second(0).valueOf();
  const endTime = dayjs().hour(23).minute(59).second(59).valueOf();
  todayApproveStatistics(startTime, endTime);
  currentMonthApproveStatistics();
  QUERY_APPROVAL_CHART_BY_TIME({ startTime, endTime }).then((res) => {
    state.timeStatistics.line = res.line;
    state.timeStatistics.content = res.content;
    getCurrentInstance()
      .page?.selectComponent('#mychart-dom-multi-line')
      .init((canvas, width, height, dpr) => {
        initLineChart(canvas, width, height, dpr);
      });
  });

  QUERY_APPROVAL_CHART_BY_STATUS({ startTime, endTime }).then((res) => {
    state.approveResultStatistics.line = res.line;
    state.approveResultStatistics.content = res.content;
    getCurrentInstance()
      .page?.selectComponent('#mychart-dom-multi-bar')
      .init((canvas, width, height, dpr) => {
        initBarChart(canvas, width, height, dpr);
      });
  });
}

//折线图
function timeLineChart() {
  const xDataList: string[] =
    state.timeStatistics.line?.map((item) => {
      return item + ':00';
    }) || [];

  const seriesList =
    state.timeStatistics.content?.map((item) => {
      return {
        name: item.typeName,
        data: item.data,
        type: 'line',
        smooth: true,
      };
    }) || [];
  const legendData =
    state.timeStatistics.content?.map((item) => {
      return item.typeName;
    }) || [];

  return {
    legend: {
      type: 'scroll',
      orient: 'horizontal',
      data: legendData,
      top: '4%',
      icon: 'rect',
      itemHeight: 5,
    },
    xAxis: {
      type: 'category',
      data: xDataList,
    },
    yAxis: {
      type: 'value',
    },
    series: seriesList,
    dataZoom: [
      {
        type: 'inside', // 内嵌入图标中
        startValue: 0, // 用绝对值的方式定义了窗口数据默认展示的数据开始范围
        endValue: 11, // 用绝对值的方式定义了窗口数据默认展示的数据终止范围
        filterMode: 'filter',
        xAxisIndex: [0],
      },
    ],
  };
}

//柱形图
function resultBar() {
  const xDataList: string[] = state.approveResultStatistics.line?.map((item) => {
    return item || '';
  }) || [''];

  let yDataList1: number[] = [];
  let yDataList2: number[] = [];
  if (state.approveResultStatistics.content && state.approveResultStatistics.content?.length > 1) {
    yDataList1 = state.approveResultStatistics.content[0].data || [0];
    yDataList2 = state.approveResultStatistics.content[1].data || [0];
  }
  console.log(yDataList1, yDataList2);

  return {
    legend: {
      orient: 'horizontal',
      data: ['通过', '拒绝'],
      top: '4%',
      icon: 'rect',
      itemHeight: 5,
    },
    xAxis: {
      type: 'category',
      data: xDataList,
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '通过',
        data: yDataList1,
        type: 'bar',
        stack: 'Ad',
      },
      {
        name: '拒绝',
        data: yDataList2,
        type: 'bar',
        stack: 'Ad',
      },
    ],
  };
}

function initLineChart(canvas, width, height, dpr) {
  const lineChart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr, // new
  });
  canvas.setChart(lineChart);
  lineChart.setOption(timeLineChart());
  return lineChart;
}

const ecLine = {
  lazyLoad: true,
};

function initBarChart(canvas, width, height, dpr) {
  const barChart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr, // new
  });
  canvas.setChart(barChart);
  barChart.setOption(resultBar());
  return barChart;
}
const ecBar = {
  lazyLoad: true,
};
</script>

<template>
  <view class="asset-approve-list app-page--1">
    <app-navbar title="变更审批" />
    <nut-tabs v-model="state.tabIndex" class="asset-approve-list__tabs">
      <nut-tab-pane title="审批列表" class="nut-tab-pane-bg">
        <nut-searchbar
          class="asset-approve-list__search"
          v-model="state.keyword"
          placeholder="请输入单号"
          @search="
            () => {
              state.activePage = 1;
              state.finished = false;
              state.list = [];
              onLoading();
            }
          "
          @clear="
            () => {
              state.activePage = 1;
              state.finished = false;
              state.list = [];
              onLoading();
            }
          "
        >
          <template v-slot:leftin>
            <app-nut-icon-search2 />
          </template>
        </nut-searchbar>
        <scroll-view
          class="scroll-view-height app-page__wrapper"
          :scroll-y="true"
          :lower-threshold="100"
        >
          <view class="asset-approve-list__wrapper">
            <view
              class="asset-approve-item"
              v-for="item in state.list"
              :key="item.id"
              @click="navigateTo({ url: `pages/asset-change/approve-detail/index?id=${item.id}` })"
            >
              <view class="asset-approve-item__header">
                <view class="asset-approve-item__header--left">{{ item.changeCode }}</view>
                <view class="asset-approve-item__header--right">
                  <text
                    class="asset-approve-item__status"
                    :style="{
                      color: item.changeStatus
                        ? ASSET_CHANGE_ALTER_STATUS_COLOR[item.changeStatus]
                        : '#999',
                      backgroundColor: item.changeStatus
                        ? ASSET_CHANGE_ALTER_STATUS_BG_COLOR[item.changeStatus]
                        : '#999',
                    }"
                  >
                    {{ item.changeStatus ? ASSET_CHANGE_ALTER_STATUS[item.changeStatus] : '-' }}
                  </text>
                </view>
              </view>
              <nut-row gutter="10">
                <nut-col span="12">
                  借出时间:&nbsp;&nbsp;{{
                    item.changeTime ? dayjs(Number(item.changeTime)).format('YYYY/MM/DD') : '-'
                  }}
                </nut-col>
                <nut-col span="12">
                  预计归还:&nbsp;&nbsp;{{
                    item.borrowStartTime
                      ? dayjs(Number(item.borrowStartTime)).format('YYYY/MM/DD')
                      : '-'
                  }}
                </nut-col>
              </nut-row>
              <nut-row gutter="10">
                <nut-col span="12"
                  >借用部门:&nbsp;&nbsp;{{ item.applicantDeptName || '-' }}</nut-col
                >
                <nut-col span="12">借用人:&nbsp;&nbsp;{{ item.applicantName || '-' }}</nut-col>
              </nut-row>
            </view>
          </view>

          <view class="app-page__list-tips">
            <text v-if="!state.list.length">暂无数据！</text>
            <text v-else-if="state.list.length && state.loading">加载中...</text>
            <text v-else-if="state.list.length && state.finished">加载完成!</text>
          </view>
        </scroll-view>
      </nut-tab-pane>
      <nut-tab-pane title="审批统计" class="nut-tab-pane-bg">
        <scroll-view
          class="scroll-view-height app-page__wrapper"
          :scroll-y="true"
          :lower-threshold="100"
        >
          <view class="asset-approve-list__wrapper2">
            <nut-cell-group>
              <nut-cell title="审批统计" />
              <nut-cell>
                <template v-slot:title>
                  <view class="asset-approve-list__visitor-wrapper">
                    <view class="asset-approve-list__visitor-total">
                      <view class="asset-approve-list__visitor-title"
                        ><text>{{ state.todayApprove || '0' }}</text></view
                      >
                      <view><text>今日审批</text></view>
                    </view>
                    <view class="asset-approve-list__visitor-arrived">
                      <view class="asset-approve-list__visitor-title"
                        ><text>{{ state.currentMonthApprove || '0' }}</text></view
                      >
                      <view><text>本月审批</text></view>
                    </view>
                  </view>
                </template>
              </nut-cell>
            </nut-cell-group>
            <nut-cell-group>
              <nut-cell title="时间分布" />
              <nut-cell>
                <template v-slot:title>
                  <view class="echarts">
                    <ec-canvas
                      id="mychart-dom-multi-line"
                      canvas-id="mychart-multi-line"
                      :ec="ecLine"
                      :force-use-old-canvas="true"
                    ></ec-canvas>
                  </view>
                </template>
              </nut-cell>
            </nut-cell-group>
            <nut-cell-group>
              <nut-cell title="审批结果" />
              <nut-cell>
                <template v-slot:title>
                  <view class="echarts">
                    <ec-canvas
                      id="mychart-dom-multi-bar"
                      canvas-id="mychart-multi-bar"
                      :ec="ecBar"
                      :force-use-old-canvas="true"
                    ></ec-canvas>
                  </view>
                </template>
              </nut-cell>
            </nut-cell-group>
          </view>
        </scroll-view>
      </nut-tab-pane>
    </nut-tabs>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
